package parser;
import java.io.*;

public class Saver extends ByteStream implements Runnable {
    
    String name;
    
    Saver(String name) {
        this.name = name;
    }
   
    public void close() throws IOException {
        super.close();
        new Thread(this).start();
    }
    
    InputStream getInput()  throws IOException {
        InputStream is = new ByteArrayInputStream(buf);    
        is.read();  // Remove version number.
        is.read();
        return is;
    }
    
    Reader getReader() throws IOException {
        Reader r = new ByteArrayReader(buf);
        r.read(); // Remove version number.
        return r;
    }

    public void run() {
        File pxc = new File(name.concat(".pxc"));
        try {
            File tmpFile = File.createTempFile("bytecode", ".pxc");
            OutputStream out = new BufferedOutputStream(new FileOutputStream(tmpFile));
            for (int i = 0; i < count; i++) {
                out.write(buf[i]);
            }
            out.close();
            tmpFile.renameTo(pxc);
            System.err.println("Saved to " + pxc.getCanonicalPath());
        } catch (IOException ioe) {
            System.err.println("Failed to save to " + pxc.getPath());
        }
    }
 
}

class ByteArrayReader extends Reader {
 
    int index;
    byte[] array;
    
    ByteArrayReader(byte[] array) {
        this.array = array;
    }
    
    public int read() {
        return (array[index++] << 8) | (array[index++] & 0xff);
    }
    
    public int read(char[] buf, int off, int len) {
        len = Math.min(len, (array.length - index) >> 1);
        for (int i = 0; i < len; i++) {
            buf[i + off] = (char)((array[index++] << 8) | (array[index++] & 0xff));
        }
        return len;
    }
    
    public void close() {
    }
    
}
